package com.dana.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.constants.CacheConstant;
import com.core.constants.Constants;
import com.dana.friend.domain.user.User;
import com.dana.friend.domain.user.vo.UserVO;
import com.dana.friend.mapper.user.UserMapper;
import com.dana.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;


    public UserVO getUserById(Long userId){
        //先查询缓存
        String userKey=getUserKey(userId);
        UserVO userVO = redisService.getCacheObject(userKey, UserVO.class);
        if (userVO!=null){
            //延长时间
            redisService.expire(userKey, Constants.TEN_MINUTES,TimeUnit.MINUTES);
            return userVO;
        }
        //缓存中没有数据,就去数据查
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,
                        User::getNickName,
                        User::getHeadImage,
                        User::getSex,
                        User::getPhone,
                        User::getEmail,
                        User::getWechat,
                        User::getSchoolName,
                        User::getMajorName,
                        User::getIntroduce)
                .eq(User::getUserId, userId));
        if (user==null){
            return null;
        }
        //刷新缓存
        refreshUser(user);
        userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        return userVO;
    }

    public void refreshUser(User user) {
       String userKey= getUserKey(user.getUserId());
       //保存10分钟
       redisService.setCacheObject(userKey,user,Constants.TEN_MINUTES, TimeUnit.MINUTES);
    }


    private String getUserKey(Long userId){
        return CacheConstant.USER_DETAIL+userId;
    }
}
